<template>
  <div class="home">
    <div class="es">
      <div class="es-poem">
        <div class="el" style="margin:10px 10px;">
          <el-button circle icon="el-icon-circle-plus-outline" type="primary" title="新增" size="small"
                     @click="rowAdd"></el-button>
          <el-button circle icon="el-icon-delete" type="primary" title="清除所有ES数据" size="small"
                     @click="delToES"></el-button>
          <el-button circle icon="el-icon-refresh" type="primary" title="加载所有DB->ES数据" size="small"
                     @click="addToEs"></el-button>

          <el-select v-model="dbFlag" placeholder="请选择数据来源" style="width: 10%;margin-left: 10%"
                     @change="remoteMethod">
            <el-option
              v-for="item in dbs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <el-select v-model="optionsValue" clearable placeholder="请选择类型" style="width: 10%">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>

          <el-input placeholder="请输入查询内容" v-model="keyword" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click.prevent="searchPoem"></el-button>
          </el-input>
          <!--分页-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,20, 30, 40,50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>


        <!--表格内容-->
        <el-table
          ref="list"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          :default-sort="{prop: 'date', order: 'descending'}"
          @row-click="handleRowClick"
          @select-all="handleCheckedAllAndCheckedNone"
          @select="handleCheckedAllAndCheckedNone"
          @sort-change="sortChange">
          <el-table-column
            type="selection"
            width="45"
            align="center">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            property="title"
            label="标题"
            width="180"
            sortable>
            <template slot-scope="scope">
              <div class="col-cont" v-html="scope.row.title"></div>
            </template>
          </el-table-column>
          <el-table-column
            property="author"
            label="作者"
            width="180">
            <template slot-scope="scope">
              <div class="col-cont" v-html="scope.row.author"></div>
            </template>
          </el-table-column>
          <el-table-column
            property="content"
            label="诗词">
            <template slot-scope="scope">
              <div class="col-cont" v-html="scope.row.content"></div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="130"
            align="center">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-edit-outline" type="primary" title="编辑" size="small"
                         @click="rowEdit(scope.$index, scope.row)"></el-button>
              <el-button circle icon="el-icon-delete" type="danger" title="删除" size="small"
                         @click="rowDel(scope.$index, scope.row, $event)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--编辑-弹出层-->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="isShowEditDialog"
          width="430px"
          @close="dialogClose">
          <el-form
            ref="editForm"
            :model="formFileds"
            label-width="55px"
            :rules="rules">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formFileds.title"></el-input>
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="formFileds.author"></el-input>
            </el-form-item>
            <el-form-item label="诗词" prop="content">
              <el-input type="textarea"
                        :rows="5" v-model="formFileds.content"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAddEdit(formFileds.title)" class="pull-right margin-l-25">确定
              </el-button>
              <el-button @click="isShowEditDialog = false" class="pull-right">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Poem",
    data() {
      return {
        formFileds: {
          title: '',
          author: '',
          content: '',
          id: ''
        },
        rules: {
          title: [
            {required: true, message: '标题不能为空', trigger: 'blur, change'}
          ],
          author: [
            {required: true, message: '作者不能为空', trigger: 'blur, change'}
          ],
          content: [
            {required: true, message: '诗词不能为空', trigger: 'blur, change'}
          ]
        },
        options: [{
          value: 'title',
          label: '标题'
        }, {
          value: 'author',
          label: '作者'
        }, {
          value: 'content',
          label: '诗词'
        }],
        dbs: [{
          value: false,
          label: 'DB'
        }, {
          value: true,
          label: 'ES'
        }],
        keyword: '',
        optionsValue: '',
        dialogTitle: '',
        tableData: [],
        isShowEditDialog: false,
        pageNo: 1,
        pageSize: 10,
        currentPage: 1,
        total: 0,
        dbFlag: false
      }
    },
    methods: {
      remoteMethod(query) {
        if (!query) {
          this.getDB();
        } else {
          this.searchPoem();
        }
      },
      sortChange(column, prop, order) {
        console.log('column:', column);
        console.log('prop:', column.prop);
        console.log('order:', column.order);
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;

        if (!this.dbFlag) {
          this.getDB();
        } else {
          this.searchPoem();
        }
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNo = val;

        if (!this.dbFlag) {
          this.getDB();
        } else {
          this.searchPoem();
        }
      },
      handleRowClick(row, event, column) {

        // 仅选中当前行
        this.setCurRowChecked(row);
      },
      handleCheckedAllAndCheckedNone(selection) {

        // 当前选中仅一行时操作-（当前表格行高亮）
        1 != selection.length && this.$refs.list.setCurrentRow();
      },
      dialogClose() {

        // 清空编辑表单
        this.$refs.editForm.resetFields();
      },
      rowAdd() {
        this.dialogTitle = '新增';
        this.isShowEditDialog = true;

      },
      delToES() {
        this.$confirm('确定要清除ES数据吗？', '删除', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$axios.delete('/poem/delAllToES').then(res => {
            this.$message.success('清除ES数据成功');
            if(!this.dbFlag){
              this.getDB();
            }else{
              this.searchPoem();
            }

          })
        })
      },
      addToEs() {
        this.$confirm('添加之前请先清空ES数据，确定要添加DB数据到ES中吗？', '添加', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$axios.post('/poem/addToES').then(res => {
            this.tableData=res.data.result;
            this.$message.success('添加成功');
          })
        })
      },
      rowEdit(index, row) {
        this.dialogTitle = '编辑';
        this.setCurRowChecked(row);
        // this.formFileds = row;
        this.editIndex = index;
        // 给编辑弹出层赋值
        //***这里需要注意的是：因为加了排序 所以tableData的顺序和实际显示的行顺序不一样
        for (let key in this.formFileds) {
          this.formFileds[key] = row[key];
        }
        this.isShowEditDialog = true;
      },
      handleAddEdit(result) {
        this.$refs.editForm.validate(isValid => {
          console.log('isValid:', isValid)
          if (!isValid) return;
          /* json格式提交： */
          let formData = JSON.stringify(this.formFileds);

          //id 空新增
          if (this.formFileds.id.length === 0) {
            this.$axios.post('/poem/add', formData).then(res => {
              this.tableData.push(res.data.result);
              this.isShowEditDialog = false;
              this.$message.success('新增成功');
            })
          } else {
            let that = this;
            this.$axios.post('/poem/upd', formData).then(res => {
              // Object.assign(this.tableData[index], this.formFileds);
              that.tableData = that.tableData.map(table => {
                if (table.id == that.formFileds.id) {
                  table = JSON.parse(formData);
                }
                return table;
              })
              this.isShowEditDialog = false;
              this.$message.success('修改成功');
            })
          }

          // // 保存编辑后的数据
          //Object.assign(this.tableData[id], this.formFileds);
          // this.isShowEditDialog = false;
          //
          // // 考虑到可能编辑了-需要重新排序
          // // ***注意：手动排序传参和表格的default-sort属性格式不太一样
          // this.$refs.list.sort('date', 'descending');
        });
      },
      rowDel(index, row, event) {
        // 让当前删除按钮失焦
        event.target.blur();
        this.$confirm('确定要删除当前行吗？', '删除', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.$axios.delete('/poem/del', {
            params: {
              id: row.id
            }
          }).then(res => {
            if (!this.dbFlag) {
              this.getDB();
            } else {
              this.searchPoem();
            }
            //this.tableData.splice(index, 1);
            this.$message.success('删除成功');
          })
          return false;
        });
      },
      // 选中当前行-当前行的复选框被勾选
      setCurRowChecked(row) {

        this.$refs.list.clearSelection();
        this.$refs.list.toggleRowSelection(row);
      },
      searchPoem() {
        this.$axios.get('/poem/get', {
          params: {
            type: this.optionsValue,
            keyword: this.keyword,
            pageNo: this.pageNo,
            pageSize: this.pageSize
          }
        }).then(res => {
          this.tableData = res.data.result;
          this.total = res.data.total;
        })
      },
      getDB() {
        this.$axios.get('/poem/getDB', {
          params: {
            type: this.optionsValue,
            keyword: this.keyword,
            pageNo: this.pageNo,
            pageSize: this.pageSize
          }
        }).then(res => {
          this.tableData = res.data.result;
          this.total = res.data.total;
        })
      }
    },
    activated() {
      console.log('dbFlag:', this.dbFlag)
      if (!this.dbFlag) {
        this.getDB();
      } else {
        this.searchPoem();
      }

    }
  }
</script>

<style scoped lang="less">
  .home {
    height: calc(~'100% - 40px');
  }

  .es {
    display: flex;
    height: 100%;
    width: 100%;
  }

  .es-poem {
    position: relative;
    width: 100%;
    background-color: @boxBgColor;
    box-shadow: 2px 2px 5px #ccc;
    overflow-y: auto;
  }

  .el-form {
    padding: 0 10px;
  }

  .el-date-editor {
    width: 100% !important;
  }

  .input-with-select {
    width: 30%;
  }
</style>
